package com.example.day1.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.day1.DTO.DishDto;
import com.example.day1.DTO.SetmealDto;
import com.example.day1.common.R;
import com.example.day1.entity.Dish;
import com.example.day1.entity.DishFlavor;
import com.example.day1.mapper.DishMapper;
import com.example.day1.service.DishFlavorService;
import com.example.day1.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl  extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Transactional
    //保证事务的一致性，不会出错
    public void savewith(DishDto dishDto){
        //保存dish表，因为dishdto时dish表的子类
    this.save(dishDto);
    //保存菜品口味到表中，难点，因为前端提交json中的数据没有id等关键字段，所以不能直接保存
        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        //将这个对象加入关键属性
      flavors=flavors.stream().map((item)->{
          item.setDishId(id);
          return item;
      }).collect(Collectors.toList());

            dishFlavorService.saveBatch(flavors);
        }

    @Override
    //主要目的是通过id获取dto对象(给dishdto赋值所需要的参数)
    public DishDto get(long id) {
        //获取dish的值
        Dish byId = dishService.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId,dishDto);
        //获取Dish_flavor中的数据
        LambdaQueryWrapper<DishFlavor> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据id获取口味列表
        objectLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(objectLambdaQueryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Transactional
    public void updatewith(DishDto dto) {
        //先更新一定啊的dish数据
        this.updateById(dto);

        long id=dto.getId();
    //清空口味表
        LambdaQueryWrapper<DishFlavor> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(DishFlavor::getDishId,dto.getId());
       dishFlavorService.remove(objectLambdaQueryWrapper);

       //获取每个口味
        List<DishFlavor> flavors = dto.getFlavors();
        flavors=flavors.stream().map((item)->{
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
            dishFlavorService.saveBatch(flavors);


    }


};

